package command

import (
	"fmt"
	"io/ioutil"
	"path/filepath"
	"strings"
)

type ConfigCommand struct{}

func (i *ConfigCommand) Desc() *CommandDesc {
	return &CommandDesc{
		Name: "config",
		Methods: []*CommandMethod{
			{
				Name: "create",
				Desc: "创建配置文件",
				Params: []*CommandParams{
					{Name: "name", Desc: "配置名称，必须加上 Conf 后缀，如: TestConf"},
				},
			},
		},
	}
}

func (i *ConfigCommand) Create(name string) {
	ParamCheck("name", name)

	project, err := ProjectName()
	HandleError(err)

	name = strings.Title(name)
	instanceName := fmt.Sprintf("%sig", name)

	projectPath := GetCurrentDir()
	typsPath := filepath.Clean(fmt.Sprintf("%s/config/typs/%s.go", projectPath, name))
	varsPath := filepath.Clean(fmt.Sprintf("%s/config/vars/%s.go", projectPath, name))
	autoloadPath := filepath.Clean(fmt.Sprintf("%s/autoload/Config.go", projectPath))

	typsContent := fmt.Sprintf("package typs\n\ntype %s struct{}\n\nfunc (i *%s) ConfigName() string {\n\treturn \"%s\"\n}\n", name, name, name)
	varsContent := fmt.Sprintf("package vars\n\nimport \"%s/config/typs\"\n\nvar %s = &typs.%s{}\n", project, instanceName, name)

	// 写typs
	err = ioutil.WriteFile(typsPath, []byte(typsContent), 0755)
	HandleError(err)

	// 写vars
	err = ioutil.WriteFile(varsPath, []byte(varsContent), 0755)
	HandleError(err)

	// 写autoload
	autoloadContent, err := ioutil.ReadFile(autoloadPath)
	HandleError(err)
	if !strings.Contains(string(autoloadContent), fmt.Sprintf("cServer.Inject(vars.%s)", instanceName)) {
		newContent := strings.ReplaceAll(string(autoloadContent), "}", fmt.Sprintf("\tcServer.Inject(vars.%s)\n}", instanceName))
		err = ioutil.WriteFile(autoloadPath, []byte(newContent), 0755)
		HandleError(err)
	}
}
